package com.tianqu.tms.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.exception.TmsDaoException;
import com.tianqu.tms.dto.SequenceDto;

public class SequenceDaoImp extends TmsDao implements SequenceDao {
	Logger logger = Logger.getLogger(this.getClass());
	
	protected SequenceDaoImp() throws TmsDaoException {
		super();
	}

	/* 
	 * 得到最新serial
	 */
	@Override
	public SequenceDto getSerial(int type) throws TmsDaoException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		SequenceDto dto = null;
		StringBuffer sql = new StringBuffer("");
		sql.append("SELECT PREFIX,POSTFIX,");
		sql.append("NOWSERIAL,ENDNUM, ");
		sql.append("TYPE ");
		sql.append(" FROM ");
		sql.append(TmsTableNames.TMS_SEQUENCE);
		sql.append(" WHERE STATUS ='1'");
	    sql.append(" AND TYPE=?");
		try {
			ps = conn.prepareStatement(sql.toString());
			ps.setInt(1, type);
			rs = ps.executeQuery();
     	while (rs.next()) {
     		dto = new SequenceDto();
     		dto.setPrefix(rs.getString("PREFIX"));
     		dto.setPostfix(rs.getString("POSTFIX"));
     		dto.setNowSerial(rs.getInt("NOWSERIAL"));
     		dto.setEndnum(rs.getInt("ENDNUM"));
     		dto.setType(rs.getInt("TYPE"));
			}
			return dto;	
		} 
		catch (SQLException e) {
			logger.error("getSerial error.",e);
			throw new TmsDaoException(e.toString());
		} finally {
			super.close(rs, ps);
		}
		
	}

	@Override
	public void updateSerial(int type,int nowSerial) throws TmsDaoException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		StringBuffer sql = new StringBuffer("");
		sql.append("UPDATE ");
		sql.append(TmsTableNames.TMS_SEQUENCE);
		sql.append(" SET ");
		sql.append("NOWSERIAL=? ");
		sql.append(" WHERE ");
		sql.append(" TYPE=? ");
		try {
			ps = conn.prepareStatement(sql.toString());
			ps.setInt(1, nowSerial);
			ps.setInt(2, type);
			ps.executeUpdate();
		} catch (SQLException e) {
			logger.error("getSerial error.",e);
			throw new TmsDaoException(e.toString());
		}finally {
			super.close(rs, ps);
		}
		
	}

	

}
